var addList = [];
var reduceList = [];
var startPosition;
var numList = [];
var direction;

function start() {
	scan();
}
function init(){
	addList = [],
	reduceList = [],
	startPosition = $("#startPosition").val();
	startPosition = Number(startPosition);
	const string = $("#numList").val();
	numList = string.split(';');
		direction = $("#direction").val();
}
function sortNumber(a,b){
	return a - b
}
function scan(){
	init();
	let addSum = 0;
	let reduceSum = 0;
	let sum = 0;
	numList.sort(sortNumber);
	numList.forEach((e)=>{
		e = Number(e);	
		if(e > startPosition){
			addList.push(e);
		}else{
			reduceList.push(e);
		}
	});
	for(var i = 0;i<addList.length-1;i++){
		addSum += addList[i+1] - addList[i];
	}
	for(var i=reduceList.length-1;i>0;i--){
		reduceSum += reduceList[i] - reduceList[i-1];
	}
	sum = reduceSum + addSum + addList[0] - startPosition + startPosition - reduceList[reduceList.length-1];
	//0减少反向，1增加反向

	if(direction === '0'){
		for(var i = reduceList.length-1;i>=0;i--){
			printText(reduceList[i] + "			");
		}
		addList.forEach((e)=>{
			printText(e + "			");
		});
		sum += startPosition - reduceList[0];
	}else{
		addList.forEach((e)=>{
			printText(e + "			");
		});
		for(var i = reduceList.length-1;i>=0;i--){
			printText(reduceList[i] + "			");
		}
		sum += addList[addList.length - 1] - startPosition;
	}
	console.log(sum);
	sum = sum / numList.length;
	printText('平均寻道长度为' + sum);
}

function printText(str) {
	$("#print").append(str)
}
